<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>使用axios发ajax请求</title>
</head>
<body>
  <button onclick="testGet()">发送GET请求</button><br>
  <button onclick="testPost()">发送POST请求</button><br>
  <button onclick="testPut()">发送PUT请求</button><br>
  <button onclick="testDelete()">发送Delete请求</button><br>

  <script src="https://cdn.bootcdn.net/ajax/libs/axios/0.21.0/axios.js"></script>
  <script>
    function testGet() {
      axios({ // 配置对象: 属性名是一些特殊名称
        method: 'GET',
        url: 'http://localhost:3000/posts',
        params: { // 指定query参数,而不是params参数
          id: 2
        }
      }).then(
        response => {
          console.log(response.data, response.status, response.statusText)
        },
        error => {
          alert(error.message)
        }
      )
    }

    function testPost() {
      axios({ // 配置对象: 属性名是一些特殊名称
        method: 'POST',
        url: 'http://localhost:3000/posts',
        data: { // 指定请求头参数数据
          title: 'ccc',
          author: 'ddd'
        }
      }).then(
        response => {
          console.log(response.data, response.status, response.statusText)
        },
        error => {
          alert(error.message)
        }
      )
    }

    function testPut() {
      axios({ // 配置对象: 属性名是一些特殊名称
        method: 'PUT',
        url: 'http://localhost:3000/posts/5',
        data: { // 指定请求头参数数据
          title: '经济金融',
          author: '王博文'
        }
      }).then(
        response => {
          console.log(response.data, response.status, response.statusText)
        },
        error => {
          alert(error.message)
        }
      )
    }

    function testDelete() {
      axios({ // 配置对象: 属性名是一些特殊名称
        method: 'DELETE',
        url: 'http://localhost:3000/posts/5',
      }).then(
        response => {
          console.log(response.data, response.status, response.statusText)
        },
        error => {
          alert(error.message)
        }
      )
    }
  </script>
</body>
</html>